package pl.project.engineering.pages;

import java.util.List;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.tapestry5.annotations.InjectPage;
import org.apache.tapestry5.annotations.Persist;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.ioc.annotations.Inject;
import pl.project.engineering.entities.AlertEmailAddress;
import pl.project.engineering.data.AlertEmailAddressList;
import pl.project.engineering.services.AppConfig;
import pl.project.engineering.data.MailServerConfig;
import pl.project.engineering.services.SerialComPort;

/**
 *
 * @author ikrzysiek
 */
@RequiresAuthentication
public class Configuration {

  @Property
  private MailServerConfig mailServerConfig;

  @Property
  private AlertEmailAddressList alertEmailAddressList;

  @Property
  private AlertEmailAddress alertEmailAddress;
  
  @Property
  @Persist
  private String portName;
  
  public enum Submit { EDIT, RECONNECT; }
  
  private Submit submit;
  
  @Inject
  private SerialComPort serialComPort;

  @Inject
  private AppConfig appConfig;
  
  @InjectPage
  private EditSerialPortName editSerialPortName;

  @InjectPage
  private Index index;
  
  @RequiresAuthentication
  Object onActivate(){
    return null;
  }

  public List<AlertEmailAddress> getAlertEmailAddresses() {
    return appConfig.getAlertEmailAddressList().getAlertEmailAddresses();
  }
  
  void onSelectedFromEdit(){
    submit = Submit.EDIT;
  }
  
  void onSelectedFromReconnect() {
    submit = Submit.RECONNECT;
  }
  
  Object onSuccess(){
    switch(submit){
      case EDIT:
        return editSerialPortName;
      case RECONNECT:
        serialComPort.setParameterAndReconnect(portName);
        return index;
    }
    return null;
  }

  void setupRender() {
    this.alertEmailAddressList = appConfig.getAlertEmailAddressList();
    this.mailServerConfig = appConfig.getMailServerConfig();
    this.portName = serialComPort.getPortName();
  }

  void onActionFromDelete(String alertEmailAddressId) {
    appConfig.getAlertEmailAddressList().deleteAlerEmailAddress(alertEmailAddressId);
    appConfig.SaveConfigFile();
  }
}
